﻿using System;
using System.Globalization;
using System.Windows.Data;
using System.Linq;

namespace Gmantis.Controls.DataGrid
{
    internal class ComboDefaultConverter : IValueConverter
    {
        // Fields
        private DataGridComboBoxColumn _column;

        // Methods
        internal ComboDefaultConverter(DataGridComboBoxColumn column)
        {
            this._column = column;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((this._column.ItemsSource == null) || (targetType != typeof(string)))
            {
                return value;
            }
            foreach (object obj2 in this._column.ItemsSource.Cast<object>())
            {
                object propertyValue;
                if (!string.IsNullOrEmpty(this._column.SelectedValuePath))
                {
                    propertyValue = obj2.GetPropertyValue<object>(this._column.SelectedValuePath);
                }
                else
                {
                    propertyValue = obj2;
                }
                if (object.Equals(value, propertyValue))
                {
                    if (!string.IsNullOrEmpty(this._column.DisplayMemberPath))
                    {
                        return obj2.GetPropertyValue<string>(this._column.DisplayMemberPath).ToString();
                    }
                    return obj2.ToString();
                }
            }
            return this.DefaultValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }

        // Properties
        public string DefaultValue { get; set; }
    }
}
